package com.heima.wemedia.service.impl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDTO;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmUserVO;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    /**
     * 登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(WmUserDTO dto) {

        //检查参数
        if (StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())){

            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"账号密码不能为空");
        }
        //查询自媒体用户
        WmUser wmUser = this.getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        if (wmUser==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        //对比密码是否正确
        String pwd = DigestUtils.md5DigestAsHex((dto.getPassword() + wmUser.getSalt()).getBytes());

        if (!wmUser.getPassword().equalsIgnoreCase(pwd)){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
        }

        //检查状态是否为9
        if (wmUser.getStatus()!=9){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR,"用户状态异常");
        }

        //修改最近登陆时间
        wmUser.setLoginTime(new Date());
        this.updateById(wmUser);


        //办法 jwt token
        String token = AppJwtUtil.getToken(Long.valueOf(wmUser.getId()));

        //将token和用户信息返回
        Map map=new HashMap();
        //将用户信息 拷贝到响应对象中
        WmUserVO wmUserVO =new WmUserVO();
        BeanUtils.copyProperties(wmUser,wmUserVO);
        map.put("token",token);
        map.put("user",wmUser);
        return ResponseResult.okResult(map);
    }
}